package com.leetcode.partition6;

import java.io.*;
import java.util.Arrays;
import java.util.PriorityQueue;

/**
 * @author `RKC`
 * @date 2022/2/3 16:02
 */
public class LC505迷宫II {

    private static final int[][] dirs = {{-1, 0}, {0, 1}, {1, 0}, {0, -1}};

    private static final BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
    private static final BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(System.out));

    public static void main(String[] args) throws IOException {
        String[] ss = reader.readLine().split(" ");
        int n = Integer.parseInt(ss[0]), m = Integer.parseInt(ss[1]);
        ss = reader.readLine().split(" ");
        int[] start = {Integer.parseInt(ss[0]), Integer.parseInt(ss[1])}, end = {Integer.parseInt(ss[2]), Integer.parseInt(ss[3])};
        int[][] maze = new int[n][m];
        for (int i = 0; i < n; i++) {
            ss = reader.readLine().split(" ");
            for (int j = 0; j < m; j++) maze[i][j] = Integer.parseInt(ss[j]);
        }
        writer.write(shortestDistance(maze, start, end) + "\n");
        writer.flush();
    }

    public static int shortestDistance(int[][] maze, int[] start, int[] destination) {
        int n = maze.length, m = maze[0].length;
        boolean[][] st = new boolean[n][m];
        int[][] dist = new int[n][m];
        for (int i = 0; i < n; i++) Arrays.fill(dist[i], 0x3f3f3f3f);
        dist[start[0]][start[1]] = 0;
        PriorityQueue<int[]> heap = new PriorityQueue<>((o1, o2) -> Integer.compare(o1[2], o2[2]));
        heap.add(new int[]{start[0], start[1], 0});
        while (!heap.isEmpty()) {
            int[] pair = heap.poll();
            int x = pair[0], y = pair[1], dis = pair[2];
            if (st[x][y]) continue;
            if (x == destination[0] && y == destination[1]) return dis;
            st[x][y] = true;
            //向4个方向滚
            for (int[] dir : dirs) {
                int nx = x + dir[0], ny = y + dir[1], nd = dis;
                while (nx >= 0 && nx < n && ny >= 0 && ny < m && maze[nx][ny] != 1) {
                    nx += dir[0];
                    ny += dir[1];
                    nd++;
                }
                nx -= dir[0];
                ny -= dir[1];
                if (dist[nx][ny] > nd) {
                    dist[nx][ny] = nd;
                    heap.add(new int[]{nx, ny, nd});
                }
            }
        }
        return -1;
    }
}
